package com.guochu.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {

    public static String postJsonData(String url , String data) {
        String result = "";
        try {
            URL postUrl = new URL(url);
            //连接
            HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            conn.setRequestProperty("charsert", "utf-8");
            conn.setRequestProperty("Content-Type",
                    "application/json");
            conn.connect();
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            out.write(data);
            out.flush();
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));//设置编码,否则中文乱码
            String line = "";
            while ((line = reader.readLine()) != null) {
                result += line;
            }
            out.close(); // flush and close
            reader.close();
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
